/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Download Sort.
 *
 * The Initial Developer of the Original Code is
 * Devon Jensen.
 *
 * Portions created by the Initial Developer are Copyright (C) 2003
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s): Devon Jensen <velcrospud@hotmail.com>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

var dsp_RDFC = '@mozilla.org/rdf/container;1';
dsp_RDFC = Components.classes[dsp_RDFC].createInstance();
dsp_RDFC = dsp_RDFC.QueryInterface(Components.interfaces.nsIRDFContainer);

var dsp_RDFCUtils = '@mozilla.org/rdf/container-utils;1';
dsp_RDFCUtils = Components.classes[dsp_RDFCUtils].getService();
dsp_RDFCUtils = dsp_RDFCUtils.QueryInterface(Components.interfaces.nsIRDFContainerUtils);

var dsp_RDF = '@mozilla.org/rdf/rdf-service;1';
dsp_RDF = Components.classes[dsp_RDF].getService();
dsp_RDF = dsp_RDF.QueryInterface(Components.interfaces.nsIRDFService);

var df_datasource;

function init() {
	
	var gIOService = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
	// From TBE
	const DIR = Components.classes['@mozilla.org/file/directory_service;1'].getService(Components.interfaces.nsIProperties);
	var dir = DIR.get('ProfD', Components.interfaces.nsILocalFile);

	var tempLocalFile = Components.classes['@mozilla.org/file/local;1'].createInstance(Components.interfaces.nsILocalFile);
	tempLocalFile.initWithPath(dir.path);

	var uri;
	try {
		uri = gIOService.newFileURI(tempLocalFile).spec;
	}
	catch(e) {}

	if (!uri.match(/\/$/)) uri += '/';
	// /from TBE
	
	df_datasource = dsp_RDF.GetDataSourceBlocking(uri + "downsort.rdf");
	
	// Add the datasources to each listbox
	var extlistelem = document.getElementById("extList");
	extlistelem.database.AddDataSource(df_datasource);
	extlistelem.builder.rebuild();
	
	var keylistelem = document.getElementById("keyList");
	keylistelem.database.AddDataSource(df_datasource);
	keylistelem.builder.rebuild();
	
	// Set the preference checkboxes to the proper values
	var pref = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
	var checkbox = document.getElementById("playSound");
    checkbox.checked = pref.getBoolPref(checkbox.getAttribute("prefstring"));
    checkbox = document.getElementById("showFile");
    checkbox.checked = pref.getBoolPref(checkbox.getAttribute("prefstring"));
    
    document.getElementById("dateFormat").selectedIndex = pref.getIntPref("downsort.dateform.us");
    checkbox = document.getElementById("showNote");
    checkbox.checked = pref.getBoolPref(checkbox.getAttribute("prefstring"));
    checkbox = document.getElementById("useRegExp");
    checkbox.checked = pref.getBoolPref(checkbox.getAttribute("prefstring"));
    
    if(checkbox.checked) {
		document.getElementById("keybox").firstChild.label = "RegExps";
		document.getElementById("selectKey").label = "RegExp";
	}
	else {
		document.getElementById("keybox").firstChild.label = "Keywords";
		document.getElementById("selectKey").label = "Keyword";
	}
}

function addToList() {
	
	var entry;
	var node;
	var childName;
	var defBool = false;  // Set to true if we're doing the default
	var whichlist;
	var rootNode;

	if (document.getElementById("selectMatch").selectedItem.id == "selectExt") {
		entry = document.getElementById("enterExt").value;
		if (entry == "") return;  // Don't want a blank extension
		// Don't want ext to start w/ period
		if (entry[0] == '.') 
			entry = entry.slice(1);
		
		rootNode = dsp_RDF.GetResource("NC:ExtensionRoot");
		childName = "NC:ExtensionRoot:" + entry.toLowerCase();
		node = dsp_RDF.GetResource(childName);
		whichlist = "extList";
		//fixClickList(entry.toLowerCase(), document.getElementById("captureClick").checked);
	}
	else if (document.getElementById("selectMatch").selectedItem.id == "selectKey") {
		entry = document.getElementById("enterKey").value;
		if (entry == "") return;  // Don't want a blank keyword
		rootNode = dsp_RDF.GetResource("NC:KeywordRoot");
		childName = "NC:KeywordRoot:" + entry.toLowerCase();
		node = dsp_RDF.GetResource(childName);
		whichlist = "keyList";
	}
	else {  // Default
		defBool = true;
		rootNode = dsp_RDF.GetResource("NC:DefaultRoot");
		node = dsp_RDF.GetResource("NC:DefaultRoot:default");	
	}
	
	// Don't let the folder location be blank
	if(document.getElementById("enterLoc").value == "") {
		alert("No folder specified");
		return;
	}
	
	var rootCont = dsp_RDFCUtils.MakeSeq(df_datasource, rootNode);
	dsp_RDFC.Init(df_datasource,rootNode);
	if(rootCont.IndexOf(node) == -1)
		rootCont.AppendElement(node);
	
	if(!defBool) // the default doesn't have this property
		rdfAddOnce(node, "http://home.netscape.com/NC-rdf#ext", entry)
	rdfAddOnce(node, "http://home.netscape.com/NC-rdf#location", document.getElementById("enterLoc").value);
	rdfAddOnce(node, "http://home.netscape.com/NC-rdf#action", document.getElementById("selectGroup").selectedItem.id);
	rdfAddOnce(node, "http://home.netscape.com/NC-rdf#saving", document.getElementById("selectStart").selectedItem.id);
	rdfAddOnce(node, "http://home.netscape.com/NC-rdf#subfolder", document.getElementById("selectSub").selectedItem.id);
	
	// Save to the datasource
	var rdfsource = df_datasource.QueryInterface(Components.interfaces.nsIRDFRemoteDataSource);
	rdfsource.Flush();
	
	// rebuild so it alpha sorts correctly, and select it in the list 
	if(!defBool) {
		var listelem = document.getElementById(whichlist);
		listelem.builder.rebuild();
		//listelem.ensureElementIsVisible(newelem); // doesn't work for some reason
		var newelem = document.getElementById(childName);
		listelem.selectItem(newelem);
	}
	else { // Give a visual indication that default settings were saved
		document.getElementById("selectDef").disabled = true;
		window.setTimeout("defaultBlinkWait()", 150);
	}
}

function defaultBlinkWait(){
	document.getElementById("selectDef").disabled = false;
}

function rdfAddOnce(node, arcText, valueText) {
	var lit = dsp_RDF.GetLiteral(valueText);
	var arc = dsp_RDF.GetResource(arcText);
		
	var targetExists = df_datasource.GetTarget(node, arc, true);
	if(targetExists != null)
		df_datasource.Change(node, arc, targetExists, lit);
	else
		df_datasource.Assert(node, arc, lit, true);
	
}
/*
function fixClickList(ext, checked) {
	var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
	try{
		var clickList = prefs.getCharPref("downsort.function.clickList");	
	} catch(e){}
	
	var inList = clickList.indexOf("," + ext + ",");
	
	if(checked) { // make sure it's in the list
		if(inList == -1) {
			clickList = clickList + ext + ","
		}
		
		// Make sure the MIMEtype is set to ask
		try {
			const ds_mimeSvc = Components.classes["@mozilla.org/mime;1"].getService(Components.interfaces.nsIMIMEService);
			MIMEInfo = ds_mimeSvc.getFromTypeAndExtension(null, ext);
			var ds_mimeDatasource = getMimeDatasource();
			var node = dsp_RDF.GetResource("urn:mimetype:handler:" + MIMEInfo.MIMEType);
			var arc = dsp_RDF.GetResource("http://home.netscape.com/NC-rdf#alwaysAsk");
			var lit = dsp_RDF.GetLiteral("true");
			
			var targetExists = ds_mimeDatasource.GetTarget(node, arc, true);
			if(targetExists != null)
					ds_mimeDatasource.Change(node, arc, targetExists, lit);
			else
					ds_mimeDatasource.Assert(node, arc, lit, true)
					
			arc = dsp_RDF.GetResource("http://home.netscape.com/NC-rdf#saveToDisk");
			lit = dsp_RDF.GetLiteral("false");
			if(targetExists != null)
					ds_mimeDatasource.Change(node, arc, targetExists, lit);
					
			// Save to the datasource
			var rdfsource = ds_mimeDatasource.QueryInterface(Components.interfaces.nsIRDFRemoteDataSource);
			rdfsource.Flush();

		} catch(e) {}
	}
	else { // remove it from the list if it's there
		if(inList != -1) {
			var clickList = clickList.replace("," + ext + ",", ",");  // replace ",ext," with ","
		}
	}
	prefs.setCharPref("downsort.function.clickList", clickList);
}

function getMimeDatasource() {
	var gIOService = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
	// From TBE
	const DIR = Components.classes['@mozilla.org/file/directory_service;1'].getService(Components.interfaces.nsIProperties);
	var dir = DIR.get('ProfD', Components.interfaces.nsILocalFile);

	var tempLocalFile = Components.classes['@mozilla.org/file/local;1'].createInstance(Components.interfaces.nsILocalFile);
	tempLocalFile.initWithPath(dir.path);

	var uri;
	try {
		uri = gIOService.newFileURI(tempLocalFile).spec;
	}
	catch(e) {}

	if (!uri.match(/\/$/)) uri += '/';
	// /from TBE

	return dsp_RDF.GetDataSourceBlocking(uri + "mimeTypes.rdf");
		
}
*/
function clearFields() {
	document.getElementById("enterExt").value = "";
	document.getElementById("enterKey").value = "";
	document.getElementById("enterLoc").value = "";
	document.getElementById("selectGroup").selectedItem = document.getElementById("selectPrompt");
	document.getElementById("selectStart").selectedItem = document.getElementById("selectAuto");
	document.getElementById("selectSub").selectedItem = document.getElementById("selectNone");
	document.getElementById("selectMatch").selectedIndex = 1; // Select the extension radio
	
	if(document.getElementById("selectStart").selectedIndex == 0) // Auto is selected
		autoClick();
	else
		promptClick();
}

function removeFromList() {
	
	var listelem, rootNode;
	if(document.getElementById("selectMatch").selectedItem.id == "selectExt") {
		listelem = document.getElementById("extList");
		rootNode = dsp_RDF.GetResource("NC:ExtensionRoot");
		//fixClickList(document.getElementById("enterExt").value, false);
	}
	else if(document.getElementById("selectMatch").selectedItem.id == "selectKey") {
		listelem = document.getElementById("keyList");
		rootNode = dsp_RDF.GetResource("NC:KeywordRoot");
	}
	else
		return;
	var itemtoremove = listelem.selectedItem;
	var newselection = listelem.getPreviousItem(itemtoremove, 1);
	
	// Remove the node from it's rootlist
	var rootCont = dsp_RDFCUtils.MakeSeq(df_datasource, rootNode);
	dsp_RDFC.Init(df_datasource,rootNode);
	var node = dsp_RDF.GetResource(itemtoremove.id);
	rootCont.RemoveElement(node, true);
	
	// Remove all the properties of the node
	var properties = df_datasource.ArcLabelsOut(node);
	while(properties.hasMoreElements()) {
    	var prop = properties.getNext();
    	var target=df_datasource.GetTarget(node,prop,true);
    	df_datasource.Unassert(node,prop,target);
    }
	
	// Save to the datasource
	var rdfsource = df_datasource.QueryInterface(Components.interfaces.nsIRDFRemoteDataSource);
	rdfsource.Flush();

	clearFields();
	listelem.selectItem(newselection);
}

function boxfocus() {

	try {
		document.getElementById("extList").toggleItemSelection(document.getElementById("extList").selectedItem);
	} catch (e) {}
	try {
		document.getElementById("keyList").toggleItemSelection(document.getElementById("keyList").selectedItem);
	} catch (e) {}
	
}

function extClick() {
	document.getElementById("enterKey").disabled = true;
	document.getElementById("enterKey").value = "";
	document.getElementById("enterExt").disabled = false;
	document.getElementById("captureClick").disabled = false;
}
function keyClick() {
	document.getElementById("enterExt").disabled = true;
	document.getElementById("enterExt").value = "";
	document.getElementById("enterKey").disabled = false;
	document.getElementById("captureClick").disabled = true;
}
function defClick() {
	document.getElementById("enterKey").disabled = true;
	document.getElementById("enterKey").value = "";
	document.getElementById("enterExt").disabled = true;
	document.getElementById("enterExt").value = "";
	document.getElementById("captureClick").disabled = true;
	
	// Populate the window with the current default values
	var node = dsp_RDF.GetResource("NC:DefaultRoot:default");
	var arcFold = dsp_RDF.GetResource("http://home.netscape.com/NC-rdf#location");
	document.getElementById("enterLoc").value = df_datasource.GetTarget(node, arcFold, true).QueryInterface(Components.interfaces.nsIRDFLiteral).Value;
	var arcAct = dsp_RDF.GetResource("http://home.netscape.com/NC-rdf#action");
	document.getElementById("selectGroup").selectedItem = document.getElementById(df_datasource.GetTarget(node, arcAct, true).QueryInterface(Components.interfaces.nsIRDFLiteral).Value);
	var arcSave = dsp_RDF.GetResource("http://home.netscape.com/NC-rdf#saving");
	document.getElementById("selectStart").selectedItem = document.getElementById(df_datasource.GetTarget(node, arcSave, true).QueryInterface(Components.interfaces.nsIRDFLiteral).Value);
	var arcSub = dsp_RDF.GetResource("http://home.netscape.com/NC-rdf#subfolder");
	document.getElementById("selectSub").selectedItem = document.getElementById(df_datasource.GetTarget(node, arcSub, true).QueryInterface(Components.interfaces.nsIRDFLiteral).Value);
	
	if(document.getElementById("selectStart").selectedIndex == 0) // Auto is selected
		autoClick();
	else
		promptClick();
}

function autoClick() {
	document.getElementById("selectGroup").disabled = false;
	document.getElementById("selectSub").disabled = false;
	document.getElementById("selectGroupLabel").disabled = false;
	document.getElementById("subFolderLabel").disabled = false;
	
}

function promptClick() {
	document.getElementById("selectGroup").disabled = true;
	document.getElementById("selectSub").disabled = true;
	document.getElementById("selectGroupLabel").disabled = true;
	document.getElementById("subFolderLabel").disabled = true;
}

function regExpClick() {
	if(!document.getElementById("useRegExp").checked) {
		document.getElementById("keybox").firstChild.label = "RegExps";
		document.getElementById("selectKey").label = "RegExp";
	}
	else {
		document.getElementById("keybox").firstChild.label = "Keywords";
		document.getElementById("selectKey").label = "Keyword";
	}
}

function extSelectList() {
	extClick();
	try {
		document.getElementById("keyList").toggleItemSelection(document.getElementById("keyList").selectedItem);
	} catch (e) {}
	document.getElementById("selectMatch").selectedItem = document.getElementById("selectExt");
	var currItem = document.getElementById("extList").selectedItem;
	document.getElementById("enterExt").value = currItem.label;
	document.getElementById("enterLoc").value = currItem.getAttribute("location");
	document.getElementById("selectGroup").selectedItem = document.getElementById(currItem.getAttribute("dupvalue"));
	document.getElementById("selectStart").selectedItem = document.getElementById(currItem.getAttribute("savingvalue"));	
	document.getElementById("selectSub").selectedItem = document.getElementById(currItem.getAttribute("subvalue"));

	if(document.getElementById("selectStart").selectedIndex == 0) // Auto is selected
		autoClick();
	else
		promptClick();
		
	var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
	var clickList = prefs.getCharPref("downsort.function.clickList");
	var inList = clickList.indexOf("," + currItem.label + ",");
	if (inList != -1)
		document.getElementById("captureClick").checked = true;
	else
		document.getElementById("captureClick").checked = false;
}

function keySelectList() {
	keyClick();
	try {
		document.getElementById("extList").toggleItemSelection(document.getElementById("extList").selectedItem);
	} catch (e) {}
	document.getElementById("selectMatch").selectedItem = document.getElementById("selectKey");
	var currItem = document.getElementById("keyList").selectedItem;
	document.getElementById("enterKey").value = currItem.label;
	document.getElementById("enterLoc").value = currItem.getAttribute("location");
	document.getElementById("selectGroup").selectedItem = document.getElementById(currItem.getAttribute("dupvalue"));
	document.getElementById("selectStart").selectedItem = document.getElementById(currItem.getAttribute("savingvalue"));
	document.getElementById("selectSub").selectedItem = document.getElementById(currItem.getAttribute("subvalue"));
	
	if(document.getElementById("selectStart").selectedIndex == 0) // Auto is selected
		autoClick();
	else
		promptClick();
}

function selectFolder() {
	
	const nsIFilePicker = Components.interfaces.nsIFilePicker;
	const nsILocalFile = Components.interfaces.nsILocalFile;
	var fp = Components.classes["@mozilla.org/filepicker;1"]
	                 .createInstance(nsIFilePicker);
	
	fp.init(window, "Select Download Directory:", nsIFilePicker.modeGetFolder);
	fp.appendFilters(nsIFilePicker.filterAll);
	var ret = fp.show();
	
	var folderField = document.getElementById("enterLoc");
	if (ret == nsIFilePicker.returnOK) {
		var localFile = fp.file.QueryInterface(nsILocalFile);
		var viewable = fp.file.path;
		folderField.value = viewable;
	}
	else if (ret == nsIFilePicker.returnCancel) {
		
	}
}

function saveSettings() {
	
	var pref = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
	var checkbox = document.getElementById("playSound");
    pref.setBoolPref(checkbox.getAttribute("prefstring"), checkbox.checked);
	checkbox = document.getElementById("showFile");
    pref.setBoolPref(checkbox.getAttribute("prefstring"), checkbox.checked);
    checkbox = document.getElementById("showNote");
    pref.setBoolPref(checkbox.getAttribute("prefstring"), checkbox.checked);
    checkbox = document.getElementById("useRegExp");
    pref.setBoolPref(checkbox.getAttribute("prefstring"), checkbox.checked);
    
    pref.setIntPref("downsort.dateform.us", document.getElementById("dateFormat").selectedIndex);
    
    /*var dateF = document.getElementById("usformat").getAttribute("selected");
    if (dateF)
    	pref.setBoolPref("downsort.dateform.us", true);
    else
    	pref.setBoolPref("downsort.dateform.us", false);*/
}